package com.wiscamp.ninechapters.problems.infrastructure.mappers.sets;

import com.wiscamp.ninechapters.problems.infrastructure.po.sets.SetProblemPO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;

/**
 * 习题集及题部分仓储对象
 *
 * @author yifeng
 */
@Repository
public interface SetProblemMapper extends JpaRepository<SetProblemPO, Long>, JpaSpecificationExecutor<SetProblemPO> {

    @Query(value = "select sp from SetProblemPO sp where sp.setId = :setId")
    Collection<SetProblemPO> findListBySet(long setId);

    @Query(value = "select max(si.problemIndex) from SetProblemPO si where si.setId = :setId")
    Integer findMaxProblemIndex(long setId);

    @Query(value = "select si.problemId from SetProblemPO si, ProblemPO i where i.problemId = si.problemId and si.setId = :setId and i.deleted = false")
    Collection<Long> findProblemIdsBySet(long setId);

    @Query(value = "select si.problemId from SetProblemPO si, ProblemPO i where i.problemId = si.problemId and si.setId in (:setIds) and i.deleted = false")
    Collection<Long> findProblemIdsBySetIds(Collection<Long> setIds);

    @Modifying
    @Transactional
    @Query(value = "delete from SetProblemPO e where e.setId = :setId and e.problemId = :problemId")
    void removeSetProblem(long setId, long problemId);
}